package httpt

import (
	"github.com/hyperway/pkg/component"
	"github.com/hyperway/pkg/constant"
	"io/ioutil"
	"net/http"
	"time"
)

type (
	// HttpTransporter 表示Http协议的后端服务
	HttpTransporter struct {
		client *http.Client
	}
)

func newTransporter() *HttpTransporter {
	return &HttpTransporter{
		client: &http.Client{
			Timeout: time.Second * 15,
		},
	}
}

func (h *HttpTransporter) Name() string {
	return constant.Http
}

func (h *HttpTransporter) DoInvoke(ctx component.InnerContext) (*component.ServerResponse, *component.ServerError) {

	service := ctx.Service()

	request, err := http.NewRequest(service.Method, service.Protocol+"://"+service.Url, nil)
	if err != nil {
		return nil, component.NewServerError(500, "New Request Error", err.Error())
	}

	response, callErr := h.client.Do(request)
	if callErr != nil {
		return nil, component.NewServerError(500, "Call Error", callErr.Error())
	}

	if response == nil {
		return nil, component.NewServerError(500, "Response Is Nil", "")
	}

	if response.StatusCode != 200 {
		return nil, component.NewServerError(response.StatusCode, "Request failed", "")
	}

	dataBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, component.NewServerError(response.StatusCode, "Response Is Nil", "")
	}

	data := string(dataBytes)

	return &component.ServerResponse{
		StatusCode: response.StatusCode,
		Data:       data,
		Headers:    response.Header,
	}, nil
}
